#!/bin/bash

# --------------------------------------------------------------------
# Create a new application directory architecture in current directory
# --------------------------------------------------------------------

# Defaults
api=ADL
tgt=bin
OldTaskItf=OFF
incpath="./inc ./itf"
srcpath="./src"

# Check parameters
function CheckParams
{
for i in $@
do
    # Check for argument
    if [ ! -z "$param" ] && [ "${i:0:1}" == "-" ]
    then
        echo Missing argument for -$param parameter
        exit 1
    fi

    case $i in

        # Help mode
        -h ) helpmode=on ;;

        # New application
        -n ) newapp=on ;;

        # Synchronize after creation
        -s ) synchro=on ;;

        # Verbose option
        -v ) vb=on ;;

        # Clean mode
        -c ) clean=on ;;

        # Ignore current wmnew.opt file
        -i ) ignore=on ;;

        # No save option
        -ns ) nosave=on ;;

        # API
        -oat   ) api=OAT ;;
        -basic ) api=OAT ;;
        -adl ) api=ADL ;;

        # Appli or Library
        -app ) tgt=bin ;;
        -lib ) tgt=lib ;;

        # Source path
        -src ) param=src ;;

        # Include path
        -inc ) param=inc ;;

        # Object path
        -extobj ) param=extobj ;;
        
        # Root Object Path
        -rootobj ) param=rootobj ;;

        # Real Object files name filter
        -objname ) param=objname ;;

        # Prefixed Object files name filter
        -objpref ) param=objpref ;;

        # Library path
        -extlib ) param=extlib ;;

        # Root Library Path
        -rootlib ) param=rootlib ;;

        # Real Library files name filter
        -libname ) param=libname ;;
        
        # Prefixed Library files name filter
        -libpref ) param=libpref ;;

        # App full path
        -path ) param=path ;;

        # Makefile name
        -name ) param=name ;;

        # Sample project
        -sample ) param=sample ;;

        # Use sample lib
        -samplelib ) param=samplelib ;;

        # Use other lib
        -otherlib ) param=otherlib ;;

        # Add compilation flag
        -flag ) param=flag ;;

        # Add an SGT flag file
        -optionfile ) param=optionfile ;;

        # Old task interface option
        -olditf ) OldTaskItf=ON ;;

        # GCC Stack Size factor
        -gssf ) param=gssf ;;
        
        # Product type
        -product ) param=product
                   echo "Warning: '-product' is a deprecated option, with no effect..." ;;

        # Version level (5 digits)
        -version ) param=version ;;

        * )
            # Check param
            case $param in

                # Source path
                src ) srcpath="$srcpath $i" ;;

                # Include path
                inc ) incpath="$incpath $i" ;;

                # Absolute Object path
                extobj ) objpath="$objpath $i" ;;
                
                # Root Object path
                rootobj ) rootobjpath="$rootobjpath $i" ;;

                # Library path
                extlib ) libpath="$libpath $i" ;;
                
                # Root Library path
                rootlib ) rootlibpath="$rootlibpath $i" ;;

                # Real Object files name filter
                objname ) objname="$objname $i" ;;

                # Prefixed Object files name filter
                objpref ) objpref="$objpref $i" ;;

                # Real Library files name filter
                libname ) libname="$libname $i" ;;

                # Prefixed Library files name filter
                libpref ) libpref="$libpref $i" ;;

                # Name
                name ) name=$i ;;

                # App full path
                path ) fullpath="$fullpath $i" ;;

                # Sample
                sample ) sample=$i
                         if [ $(pwd) != $WMATHOME/Samples/$i ]
                         then
                             # Use sample wmnew.opt only if not the same than current directory...
                             AddParamList=$(cat $WMATHOME/Samples/$i/wmnew.opt 2> /dev/null)
                         fi ;;

                # Use samplelib
                samplelib ) sampleliblist="$sampleliblist $i" ;;

                # Use other lib
                otherlib ) otherliblist="$otherliblist $i" ;;

                # Add compilation flag
                flag ) flaglist="$flaglist $i" ;;

                # GCC Stack Size factor
                gssf ) StackSizeFactor=$i ;;

                # Product Type
                product ) ProductType=$i ;;

                # Version Level
                version ) Version=$i ;;

                # SGT Option file
                optionfile ) OptFileList="$OptFileList $i" ;;

                * ) echo Unknown parameter : \"$i\", try wmnew -h for help...
                    exit 1 ;;

            esac

            oldparam=$param
            param="";;

    esac
    
    # Update full sample options list
    if [ $i != -sample ] && [ "$oldparam" != sample ]\
    && [ $i != -samplelib ] && [ "$oldparam" != samplelib ]\
    && [ $i != -name ] && [ "$oldparam" != name ]\
    && [ $i != -v ]\
    && [ $i != -s ]\
    && [ $i != -n ]\
    && [ $i != -c ]\
    && [ $i != -h ]\
    && [ $i != -i ]
    then
        FullOptList="$FullOptList $i"
    fi
    
    oldparam=""
done

# Check for argument
if [ ! -z "$param" ]
then
    echo Missing argument for -$param parameter
    exit 1
fi
}

# Check parameters
CheckParams $@
FirstSample=$sample

# Go through -sample options to parse wmnew.opt files
while [ ! -z "$AddParamList" ]
do
    # Save options
    ParamToParse=$AddParamList
    unset AddParamList
    CheckParams $ParamToParse
done

# Finaly use the current wmnew.opt option file
if [ -f wmnew.opt ] && [ "$ignore" != on ]
then
    CheckParams $(cat wmnew.opt)
fi

# Help mode
if [ "$helpmode" == on ]
then
    cat $WMATHOME/TgtGen/WmGen/wmnew.hlp
    exit
fi

# Check environment...
echo Check environment settings...
if [ -z "$WMCOMPILER" ] || [ -z "$WMMEMORY" ] || [ -z "$WMCORESW" ]
then
    # Environment is not correctly installed
    echo
    echo The Open AT environment is not correctly installed.
    echo Please run the \$WMATHOME/TgtGen/WmGen/wmcheck script and refer to the Tools Manual.
    exit 3
fi

# Clean mode
if [ "$clean" == on ]
then
    if [ "$vb" == on ]; then echo "Cleaning existing workspaces..."; fi
    
    # Remove files
    for i in $(ls *.opt *.ncb 2> /dev/null)
    do
        if [ $i != wmnew.opt ]
        then
            # Do not remove wmnew.opt file
            rm -f $i
        fi
    done
fi

# New application option
if [ "$newapp" == on ]
then
    # Same thing than New_Project sample
    if [ "$api" == ADL ]
    then
        sample=adl/generic/New_Project
    else
        sample=basic/New_Project
    fi
    FirstSample=$sample
fi

# Sample : add full path
if [ ! -z "$sample" ]
then
    # Check if the sample exist
    if [ ! -d $WMATHOME/Samples/$FirstSample ]
    then
        echo The $FirstSample sample does not exist...
        exit 2
    fi
    
    # Copy files if we are in a new directory
    if [ $(pwd) != $WMATHOME/Samples/$FirstSample ]
    then
        echo Copying $FirstSample sample files...
        cp -p -R $WMATHOME/Samples/$FirstSample/inc \
                 $WMATHOME/Samples/$FirstSample/itf \
                 $WMATHOME/Samples/$FirstSample/src \
                 $WMATHOME/Samples/$FirstSample/libs \
                 $WMATHOME/Samples/$FirstSample/*.txt \
                 $WMATHOME/Samples/$FirstSample/*.html . 2> /dev/null
        
        # Different process for libraries or samples
        if [ "${FirstSample%/*}" == adl/generic/Libraries ]
        then
            # Libraries relative path
            RelPath=../../../../../
        else
            # Binaries relative path
            RelPath=../../../../
        fi
        
        # Post-process HTML file to point to WMATHOME WebResources
        for i in $(ls *.html 2> /dev/null)
        do
            # Process file to update with WMATHOME absolute path
            # and with relative generic Libraries path
            wmtxtpp $RelPath "file://$(echo $WMATHOME_DOS | sed -e 's|\\|/|g')/" "../generic/Libraries" "Libraries" $i
        done
    fi
    
    # Set adl API if needed
    if [ ${sample:0:3} == adl ]
    then
        api=ADL
        
        # Update saved options list
        FullOptList="$FullOptList -adl"
    else
        api=OAT
        
        # Update saved options list
        FullOptList="$FullOptList -basic"
    fi

    # Set lib or bin if needed
    if [ ! -z "$(echo $sample | grep Libraries)" ]
    then
        tgt=lib
        
        # Update saved options list
        FullOptList="$FullOptList -lib"
    fi

    # Set name
    if [ -z "$name" ]
    then
        name=${FirstSample##*/}
    fi
fi

# Check name
if [ -z "$name" ]
then
    # First check for existing .scs file
    ScsList=$(ls *.scs 2> /dev/null)
    if [ ! -z "$ScsList" ]
    then
        name=$(echo $ScsList | sed -e "s/\([^ ]*\)\.scs[ ]*.*/\1/")
    else
        name=$tgt
    fi
fi

if [ "$vb" == on ]; then echo "Project name : $name"; fi

# Set synchro options
# Synchro option if needed
if [ "$synchro" == on ]
then
    SyncOpt="-s"
fi

# Verbose option if needed
if [ "$vb" == on ]
then
    SyncOpt="$SyncOpt -v"
fi

# Ignore option if needed
if [ "$ignore" == on ]
then
    IgnoreOpt="-i"
fi

# No save option if needed
if [ "$nosave" == on ]
then
    IgnoreOpt="$IgnoreOpt -ns"
fi

if [ "$vb" == on ]; then echo "Browsing used root libraries list..."; fi

# Root libraries: also synchronizes project
for i in $rootlibpath
do
    # Check existence
    if [ -d $i ]
    then
        # Ready to launch sub-process
        cd $i
        
        # Check for already existing name
        if [ -z "$(ls *.scs 2> /dev/null)" ]
        then
            # Touch an scs file to put a name on the project...
            touch $(basename $i).scs
        fi
        
        # Launch sub-process
        wmnew $SyncOpt
        
        # Check error return
        retcode=$?
        if [ $retcode -gt 0 ]
        then
            # Exit if wmnew child process failed
            exit $retcode
        fi
        
        # Go back...
        cd -
    fi
done

if [ "$vb" == on ]; then echo "Browsing used sample libraries list..."; fi

# Sample library : add interface path and library paths
for i in $sampleliblist
do
    # Check if we are currently building a sample library
    if [ $(cd ..; basename $(pwd)) == Libraries ]
    then
        # Already Building a library...
        SubPath=".."
    else
        # Building an application...
        SubPath="../Libraries"
    fi
    
    # Create Directory if not yet exist
    if [ ! -d $SubPath/$i ]
    then
        # Make directory
        mkdir -p $SubPath/$i
    fi
    
    # Update also Sample lib project
    
    # Copy files
    cd $SubPath/$i
    wmnew -sample adl/generic/Libraries/$i $SyncOpt $IgnoreOpt
    
    # Check error return
    retcode=$?
    if [ $retcode -gt 0 ]
    then
        # Exit if wmnew child process failed
        exit $retcode
    fi
    
    # Go back...
    cd -
    
    # Add interface path
    incpath="$incpath $SubPath/$i/itf"
    FullOptList="$FullOptList -inc $SubPath/$i/itf"

    # Add root library path
    rootlibpath="$rootlibpath $SubPath/$i"
    FullOptList="$FullOptList -rootlib $SubPath/$i"

    # Add prefixed library name
    libpref="$libpref $i"
    FullOptList="$FullOptList -libpref $i"
done

if [ "$vb" == on ]; then echo "Browsing provided full paths list..."; fi

# Full path : check for src, inc and itf path
for i in $fullpath
do
    ThePath=$(echo "$i" | sed -e "s/(/{/g;s/)/}/g")
    ThePath=$(eval "echo $ThePath")

    # Check path
    if [ ! -d $ThePath ]
    then
        echo Warning : \"$ThePath\" path not found...
    fi

    # Add src path
    srcpath="$srcpath $i/src"

    # Check for inc path
    if [ -d $ThePath/inc ]
    then
        incpath="$incpath $i/inc"
    fi

    # Check for itf path
    if [ -d $ThePath/itf ]
    then
        incpath="$incpath $i/itf"
    fi
done

# Copy Xml Template
echo Building $name project settings file...
cp $WMATHOME/TgtGen/WmGen/template/template.scs $name.scs

if [ "$vb" == on ]; then echo "Set project options..."; fi

# Check for SDK version
SDKVersion=""
if [ -f $WMATHOME/TgtGen/version ]
then
    # Retrieve version tag
    SDKVersion=$(cat $WMATHOME/TgtGen/version)
fi

# Set Project options
wmtxtpp "{NAME}" "$name" "{PROJECT}" "$tgt" "{API}" "$api" "{GCC_STACK_FACTOR}" "$StackSizeFactor" "{VERSION}" "$Version" "{SDKVERSION}" "$SDKVersion" $name.scs

if [ "$vb" == on ]; then echo "Updating flags list..."; fi

# Always add the Open AT version flag
flaglist="$flaglist __OAT_API_VERSION__=304"

# Set option files list if any
if [ ! -z "$OptFileList" ]
then
    # Browse flag files list
    for i in $OptFileList
    do
        # Display options
        flaglist="$flaglist $(wmdisp $i PP_OPT_COMMON)"
    done
fi

# Set flags if any
if [ ! -z "$flaglist" ]
then
    wmtxtpp "</Flags>" "$(for i in $flaglist; do echo '<Flag>'$i'</Flag>'; done)
</Flags>" $name.scs
fi

if [ "$vb" == on ]; then echo "Building include paths table..."; fi

# Build include path table
declare -i IncPathNb=0
declare -a IncPathTable
for i in $incpath
do
    IncPathTable[$IncPathNb]=$i
    IncPathNb=$(( IncPathNb + 1 ))
done
IncPathNb=$(( IncPathNb - 1 ))

if [ "$vb" == on ]; then echo "Updating include paths list..."; fi

# Set include paths
wmtxtpp "</IncludePath>" "$(for i in $(seq 0 $IncPathNb); do echo '<IncPath ref="'$i'">'${IncPathTable[$i]}'</IncPath>'; done)
</IncludePath>" $name.scs

if [ "$vb" == on ]; then echo "Building include files table..."; fi

# Build include list
inclist=""
for i in $(seq 0 $IncPathNb)
do
    # Convert environment vars for listing
    ThePath=$(echo "${IncPathTable[i]}" | sed -e "s/(/{/g;s/)/}/g")
    ThePath=$(eval "echo $ThePath")
    
    # List files
    for j in $(ls $ThePath/*.[hH] 2> /dev/null)
    do
        inclist="<IncFile ref=\"$i\">$(basename $j)</IncFile>
$inclist"
    done
done

if [ "$vb" == on ]; then echo "Updating include files list..."; fi

# Set Include list
wmtxtpp "</Headers>" "${inclist}</Headers>" $name.scs

if [ "$vb" == on ]; then echo "Updating Addon libraries list..."; fi

# Set Addon list if any
if [ ! -z "$otherliblist" ]
then
    wmtxtpp "</Addons>" "$(for i in $otherliblist; do echo '<UseAddon>'$i'</UseAddon>'; done)
</Addons>" $name.scs
fi

if [ "$vb" == on ]; then echo "Building source paths table..."; fi

# Build source path table
declare -i SrcPathNb=0
declare -a SrcPathTable
for i in $srcpath
do
    SrcPathTable[$SrcPathNb]=$i
    SrcPathNb=$(( SrcPathNb + 1 ))
done
SrcPathNb=$(( SrcPathNb - 1 ))

if [ "$vb" == on ]; then echo "Updating source paths list..."; fi

# Set source paths
wmtxtpp "</SourcePath>" "$(for i in $(seq 0 $SrcPathNb); do echo '<SrcPath ref="'$i'">'${SrcPathTable[$i]}'</SrcPath>'; done)
</SourcePath>" $name.scs

if [ "$vb" == on ]; then echo "Building source files table..."; fi

# Build source list
srclist=""
asmlist=""
for i in $(seq 0 $SrcPathNb)
do
    # Convert environment vars for listing
    ThePath=$(echo "${SrcPathTable[i]}" | sed -e "s/(/{/g;s/)/}/g")
    ThePath=$(eval "echo $ThePath")
    
    # List C files
    for j in $(ls $ThePath/*.[cC] 2> /dev/null)
    do
        # Get file name
        filename=$(basename $j)
        
        # Add file only if it is not already present
        if [ "${srclist/>${filename}</}" == "$srclist" ]
        then
            srclist="<SrcFile ref=\"$i\">${filename}</SrcFile>
$srclist"
        fi
    done
    
    # List asm files
    for j in $(ls $ThePath/*.[aA][sS][mM] 2> /dev/null)
    do
        asmlist="<AsmFile ref=\"$i\">$(basename $j asm)</AsmFile>
$asmlist"
    done
done

if [ "$vb" == on ]; then echo "Updating source files list..."; fi

# Set Source list
wmtxtpp "</Sources>" "${srclist}</Sources>" "</AsmSources>" "${asmlist}</AsmSources>" $name.scs

if [ "$vb" == on ]; then echo "Building object paths table..."; fi

# Build object path table
declare -i ObjPathNb=0
declare -a ObjPathTable
declare -a ObjPathTypeTable
for i in $objpath
do
    ObjPathTable[$ObjPathNb]=$i
    ObjPathTypeTable[$ObjPathNb]=absolute
    ObjPathNb=$(( ObjPathNb + 1 ))
    ObjExist=yes
done
for i in $rootobjpath
do
    ObjPathTable[$ObjPathNb]=$i
    ObjPathTypeTable[$ObjPathNb]=root
    ObjPathNb=$(( ObjPathNb + 1 ))
    ObjExist=yes
done
ObjPathNb=$(( ObjPathNb - 1 ))

# Set object paths
if [ "$ObjExist" == yes ]
then
    if [ "$vb" == on ]; then echo "Updating object paths list..."; fi
    
    wmtxtpp "</ObjectPath>" "$(for i in $(seq 0 $ObjPathNb); do echo '<ObjPath ref="'$i'" type="'${ObjPathTypeTable[$i]}'">'${ObjPathTable[$i]}'</ObjPath>'; done)
</ObjectPath>" $name.scs

    if [ "$vb" == on ]; then echo "Building object files table..."; fi
    
    # Build object list
    objlist=""
    for i in $(seq 0 $ObjPathNb)
    do
        # Convert environment vars for listing
        ThePath=$(echo "${ObjPathTable[i]}" | sed -e "s/(/{/g;s/)/}/g")
        ThePath=$(eval "echo $ThePath")

        # List real files
        for j in $objname
        do
            # Check File existence
            if [ "${ObjPathTypeTable[$i]}" == absolute ]
            then
                # Absolute Path
                TheFile=$(ls $ThePath/$j 2> /dev/null)
            else
                # Root project Path
                TheFile=$(ls $ThePath/*/out/$j 2> /dev/null)
            fi
            if [ ! -z "$TheFile" ]
            then
                # Browse found list
                for k in $TheFile
                do
                    # Get obj name
                    ObjectFile=$(basename $k)
                    
                    # If not yet added, add it
                    CmdRet=$(echo "$ObjectAdded" | grep " $ObjectFile ")
                    if [ -z "$CmdRet" ]
                    then
                        # Add it to list
                        ObjectAdded=" $ObjectFile $ObjectAdded"
                        
                        objlist="<ObjFile ref=\"$i\" type=\"real\">$ObjectFile</ObjFile>
$objlist"
                    fi
                done
            fi
        done
        
        # List prefixed files
        for j in $objpref
        do
            # Check File existence
            if [ "${ObjPathTypeTable[$i]}" == absolute ]
            then
                # Absolute Path
                TheFile=$(ls $ThePath/*_$j.[oO] $ThePath/*_$j.[oO][bB][jJ] 2> /dev/null)
            else
                # Root project Path
                TheFile=$(ls $ThePath/*/out/*_$j.[oO] $ThePath/*/*_$j.[oO][bB][jJ] 2> /dev/null)
            fi
            if [ ! -z "$TheFile" ]
            then
                objlist="<ObjFile ref=\"$i\" type=\"prefixed\">$j</ObjFile>
$objlist"
            fi
        done
    done

    if [ "$vb" == on ]; then echo "Updating object files list..."; fi
    
    # Set Object list
    wmtxtpp "</Objects>" "$objlist</Objects>" $name.scs
fi

if [ "$vb" == on ]; then echo "Building library paths table..."; fi

# Build Library path table
declare -i LibPathNb=0
declare -a LibPathTable
declare -a LibPathTypeTable
for i in $libpath
do
    LibPathTable[$LibPathNb]=$i
    LibPathTypeTable[$LibPathNb]=absolute
    LibPathNb=$(( LibPathNb + 1 ))
    LibExist=yes
done
for i in $rootlibpath
do
    LibPathTable[$LibPathNb]=$i
    LibPathTypeTable[$LibPathNb]=root
    LibPathNb=$(( LibPathNb + 1 ))
    LibExist=yes
done
LibPathNb=$(( LibPathNb - 1 ))

# Set Lib paths
if [ "$LibExist" == yes ]
then
    if [ "$vb" == on ]; then echo "Updating library paths list..."; fi
    
    wmtxtpp "</LibraryPath>" "$(for i in $(seq 0 $LibPathNb); do echo '<LibPath ref="'$i'" type="'${LibPathTypeTable[$i]}'">'${LibPathTable[$i]}'</LibPath>'; done)
</LibraryPath>" $name.scs

    if [ "$vb" == on ]; then echo "Building library files table..."; fi
    
    # Build Lib list
    Liblist=""
    for i in $(seq 0 $LibPathNb)
    do
        # Convert environment vars for listing
        ThePath=$(echo "${LibPathTable[i]}" | sed -e "s/(/{/g;s/)/}/g")
        ThePath=$(eval "echo $ThePath")

        # List real files
        for j in $libname
        do
            # Check File existence
            if [ "${LibPathTypeTable[$i]}" == absolute ]
            then
                # Absolute Path
                TheFile=$(ls $ThePath/$j 2> /dev/null)
            else
                # Root project Path
                TheFile=$(ls $ThePath/*/out/$j 2> /dev/null)
            fi
            if [ ! -z "$TheFile" ]
            then
                Liblist="<LibFile ref=\"$i\" type=\"real\">$j</LibFile>
$Liblist"
            fi
        done
        
        # List prefixed files
        for j in $libpref
        do
            # Check File existence
            if [ "${LibPathTypeTable[$i]}" == absolute ]
            then
                # Absolute Path
                TheFile=$(ls $ThePath/*_$j.[lL][iI][bB] 2> /dev/null)
            else
                # Root project Path : just check .scs file
                TheFile=$(ls $ThePath/${j}.scs 2> /dev/null)
            fi
            if [ ! -z "$TheFile" ]
            then
                Liblist="<LibFile ref=\"$i\" type=\"prefixed\">$j</LibFile>
$Liblist"
            fi
        done
    done

    if [ "$vb" == on ]; then echo "Building library files table..."; fi
    
    # Set Lib list
    wmtxtpp "</Libraries>" "$Liblist</Libraries>" $name.scs
fi

# Add interface files : Check API
if [ $api == ADL ]
then
    # Go to ADL interface directory
    InterfaceDir=$WMATHOME/TgtGen/Adl/Headers
else
    # Go to Basic interface directory
    InterfaceDir=$WMATHOME/TgtGen/WmHeader
fi

# List files and go back
InterfaceList=$(ls $InterfaceDir/*.h 2> /dev/null | sed -e "s|$WMATHOME|\$(WMATHOME)|g")

# Check for ADL
if [ $api == ADL ]
then
    # Add included wm_* files
    AddItfFiles=$(grep '#include .wm_' $InterfaceDir/adl_global.h | sed -e 's|#include "\([^"]*\)".*|\$(WMATHOME)/TgtGen/WmHeader/\1|g')
    InterfaceList="$InterfaceList $AddItfFiles"
fi

if [ "$vb" == on ]; then echo "Adding interface files list..."; fi

# Add interface list
wmtxtpp "</Interface>" "$(for i in $InterfaceList; do echo '<ItfFile>'$i'</ItfFile>'; done)
</Interface>" $name.scs

# Synchronize if requested
if [ "$synchro" == on ]
then
    if [ "$vb" == on ]; then echo "Building required IDE workspaces..."; fi
    
    wmsync $name
    
    # Save return code
    retcode=$?
    
    # Increase return code with wmnew error base
    if [ $retcode -gt 0 ]
    then
        retcode=$(( retcode + 3 ))
        
        # And exit with error code
        echo "wmsync error..."
        exit $retcode
    fi
fi

# Save options list if any
if [ ! -z "$FullOptList" ] && [ "$nosave" != on ]
then
    if [ "$vb" == on ]; then echo "Saving options to wmnew.opt"; fi
    
    echo "$FullOptList" > wmnew.opt
fi
